<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上拉加载</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #outter {
            width: 100%;
            height: 100vh;
            overflow-y: scroll;
            background-color: skyblue;
        }

        .inner {
            text-align: center;
            width: 80%;
            height: 200vh;
            background-color: thistle;
        }
    </style>
</head>

<body>
    <div id="outter">
        <div class="inner"></div>
    </div>

    <script>
        let outter = document.querySelector("#outter")
        let colorCount = 0;
        let gap = 30;

        // 2、节流函数体
        function throttle(fn) {
            // 4、通过闭包保存一个标记
            let canRun = true;
            return function () {
                // 5、在函数开头判断标志是否为 true，不为 true 则中断函数
                if (!canRun) {
                    return;
                }
                // 6、将 canRun 设置为 false，防止执行之前再被执行
                canRun = false;
                // 7、定时器
                setTimeout(() => {
                    fn.call(this, arguments);
                    // 8、执行完事件（比如调用完接口）之后，重新将这个标志设置为 true
                    canRun = true;
                }, 500);
            };
        }

        outter.addEventListener("scroll", throttle(function (e) {
            let outterClientHeight = outter.clientHeight,
                outterScrollTop = outter.scrollTop,
                outterScrollHeight = outter.scrollHeight

            if (outterClientHeight + outterScrollTop > outterScrollHeight - gap) {
                /* inner2.style.display = "block" */
                let newInner = document.createElement("div");
                newInner.classList.add("inner")
                if (colorCount % 2 == 0) {
                    newInner.style.backgroundColor = "thistle"
                } else {
                    newInner.style.backgroundColor = "#FFF"
                }
                colorCount++;
                outter.appendChild(newInner);
                console.log("节点插入成功")
            }
        }))
    </script>
</body>

</html>